package com.mall.alipay.handler;

import com.alibaba.fastjson.JSON;
import com.mall.alipay.common.R;
import com.mall.alipay.common.ResultCodeEnum;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationExceptionHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws
            IOException {
        if (e instanceof InsufficientAuthenticationException) {
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSON.toJSONString(R.setResult(ResultCodeEnum.NOT_SIGN_IN)));
        }
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

    }
}

